import { useState, useCallback, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from 'react-router-dom';
import CompanyAccountService from "../../app/services/companyAccountService";
import { showNotification } from "../common/headerSlice";
import Pagination from "../../components/Pagination";
import LockClosedIcon from "@heroicons/react/24/outline/LockClosedIcon";
import LockOpenIcon from "@heroicons/react/24/outline/LockOpenIcon";

import PencilIcon from "@heroicons/react/24/outline/PencilIcon";
import CommonService from "../../app/services/commonService";
import PlusIcon from "@heroicons/react/24/outline/PlusIcon";
import TitleCard from "../../components/Cards/TitleCard";
import { RoleType } from "../../app/const/const";
import ConfirmDialog from "../../components/ConfirmDialog";
import _ from "lodash";
import { set } from "react-hook-form";

function CompanyAccount() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [data, setData] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [total, setTotal] = useState(0);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [selectedId, setSelectedId] = useState(0);

  const fetchData = useCallback(() => {
    CommonService.setLoading(true);
    CompanyAccountService.list({ keyword: '', pageIndex: pageIndex }).then((res) => {
      if (res.success) {
        setData(res.data);
        setTotal(res.total);
      } else {
        dispatch(
          showNotification({
            message: "获取数据失败",
            status: "error",
          })
        );
      }
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }, [pageIndex]);

  useEffect(() => {
    fetchData();
  }, [pageIndex]);


  //编辑机构账号
  const editCompanyAccount = (id) => {
    navigate(`/app/companyAccount/edit/${id}`);
  }
  //冻结解冻机构账号
  const freezeCompanyAccount = (id) => {
    setSelectedId(id);
    setShowConfirmDialog(true);
  }

  const onPageChange = (pageIndex) => {
    setPageIndex(pageIndex);
  }

  const onCancel = () => {
    setShowConfirmDialog(false);
    setSelectedId(0);
  }

  const onSuccess = () => {
    CompanyAccountService.freeze(selectedId).then((res) => {
      if (res.success) {
        dispatch(
          showNotification({
            message: "冻结成功",
            status: "success",
          })
        );
        fetchData();
      } else {
        dispatch(
          showNotification({
            message: "冻结失败",
            status: "error",
          })
        );
      }
    });
    setShowConfirmDialog(false);
    setSelectedId(0);
  }

  return (
    <>

      <ConfirmDialog title="提示" showModel={showConfirmDialog} onCancel={onCancel} onSuccess={onSuccess}><div className=" text-sm">确认冻结规划师?</div></ConfirmDialog>
      <div className="flex flex-col">
        <TitleCard title="规划师管理" topMargin="mt-2" TopSideButtons={
          (<div className="inline-block"><button className="btn btn-sm bg-primary text-white" onClick={() => navigate("/app/companyAccount/edit/0")}><PlusIcon className="w-4 h-4" />新增规划师</button></div>)} >
          <table className="table table-zebra bg-base-100 rounded-sm  border-1">
            <thead>
              <tr className=" border-b-2 border-base-100">
                <th>序号</th>
                <th>机构名称</th>
                <th>登录名</th>
                <th>昵称</th>
                <th>邮箱</th>
                <th>电话</th>
                <th>角色</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {data && data.length > 0 ? (
                data.map((item, index) => {
                  return (
                    <tr key={index}>
                      <th>{(pageIndex - 1) * 10 + index + 1}</th>
                      <td className=" text-center">{item.companyName}</td>
                      <td className=" text-center">{item.loginName}</td>
                      <td className=" text-center">{item.nickName}</td>
                      <td className=" text-center">{item.email}</td>
                      <td className=" text-center">{item.phone}</td>
                      <td className=" text-center">{RoleType[item.roleType]}</td>
                      <td className=" text-center">{item.status === 1 ? "正常" : "禁用"}</td>
                      <td className=" text-center">
                        <div className="flex flex-row items-center justify-around ">
                          <button className="btn btn-sm text-green-500 btn-link" onClick={() => editCompanyAccount(item.accountId)}><PencilIcon className="w-4 h-4" />  编辑</button>
                          <button className={`btn btn-sm ${item.status === 1 ? 'text-red-500' : 'text-green-500'} btn-link`} onClick={() => freezeCompanyAccount(item.accountId)}>
                            {item.status === 1 ? <LockClosedIcon className="w-4 h-4" /> : <LockOpenIcon className="w-4 h-4" />}
                            {item.status === 1 ? "锁定" : "启用"}
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan="7">暂无数据</td>
                </tr>
              )}
            </tbody>
          </table>
          <div className="flex flex-row items-center justify-center">
            <Pagination currentPage={pageIndex} totalCount={total} onPageChange={onPageChange} />
          </div>
          <div className="flex flex-row items-start justify-between text-xs my-2 p-2 bg-base-300 rounded-md" style={{ lineHeight: '20px' }}>
            规划师管理负责创建管理员的下级规划师，规划师可以在分配考生后在考生管理的考生列表页面通过操作【规划师志愿单】对考生的志愿单进行增删操作。
          </div>
        </TitleCard>
      </div>
    </>
  );
}

export default CompanyAccount;
